package com.sojoys.artifact.plugin.rmi;

import java.io.IOException;
import java.rmi.NoSuchObjectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMISocketFactory;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.jfinal.plugin.IPlugin;
import com.sojoys.artifact.constant.ConfigConstant;
import com.sojoys.artifact.manager.PropManager;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

/**
 * @author : DengYing
 * @CreateDate : 2017年6月27日 下午3:53:51
 * @Description ：RMI 插件
 */
public class RmiPlugin implements IPlugin {
	static Log log = LogFactory.get(RmiPlugin.class);

	private String host = PropManager.get(ConfigConstant.RMI_HOST, "127.0.0.1");
	private int socketPort = PropManager.getInt(ConfigConstant.RMI_PORT,1099);
	private int serverSocketPort = 0;
	private Registry registry = null;
	private List<RmiServer> rmiServers = Lists.newArrayList();

	
	public RmiPlugin addRmiServer(RmiServer rmiServer){
		rmiServers.add(rmiServer);
		return this;
	}
	
	@Override
	public boolean start() {
		try {
			try {
				// 指定通信端口
				RMISocketFactory.setSocketFactory(new SMRMISocket(serverSocketPort));
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			// 指定服务器端口
			System.setProperty("java.rmi.server.hostname", host);


			registry = LocateRegistry.createRegistry(socketPort);

			// 将远程对象实例绑定到rmi:///Rem上
			List<String> names = Lists.newArrayList();
			for (RmiServer reiServer : rmiServers) {
				registry.rebind(reiServer.getRmiName(), reiServer);
				names.add(reiServer.getRmiName());
			}
//			Naming.bind(name,remote); 

			log.info("本地RMI启动成功 , host : {}, port : {} , rmi_name : {}", host, socketPort,  Joiner.on(",").join(names));
		} catch (Exception e) {
			e.printStackTrace();
			log.error("本地RMI启动异常:", e);
		}
		return true;
	}

	@Override
	public boolean stop() {
		if (registry != null) {
			try {
				for (RmiServer reiServer : rmiServers) {
					registry.unbind(reiServer.getRmiName());
				}
			} catch (RemoteException | NotBoundException e) {
				log.error("Registry unbind ", e);
			}
			try {
				UnicastRemoteObject.unexportObject(registry, true);
			} catch (NoSuchObjectException e) {
				log.error("Registry unexportObject " + e);
			}
		}
		for (RmiServer reiServer : rmiServers) {
			if (reiServer != null) {
				try {
					UnicastRemoteObject.unexportObject(reiServer, true);
				} catch (NoSuchObjectException e) {
					log.error("rmiServer unexportObject ", e);
					e.printStackTrace();
				}
			}
		}
		log.error("RMI服务停止完成");
		return true;
	}

}
